package com.config;

import com.bean.WebsiteVisitorAbnormal;
import com.mapper.repository.mysql.WebsiteVisitorAbnormalRepository;
import com.mapper.repository.mysql.WebsiteVisitorDisableRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Component
public class FilterVisit implements Filter {

    private WebsiteVisitorAbnormalRepository websiteVisitorAbnormalRepository;

    private WebsiteVisitorDisableRepository websiteVisitorDisableRepository;

    public FilterVisit(WebsiteVisitorAbnormalRepository websiteVisitorAbnormalRepository,WebsiteVisitorDisableRepository websiteVisitorDisableRepository) {
        this.websiteVisitorAbnormalRepository = websiteVisitorAbnormalRepository;
        this.websiteVisitorDisableRepository = websiteVisitorDisableRepository;
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //System.out.println("经过过滤器");
        String addr = request.getRemoteAddr();
        //判断是否被禁止访问
        int disableCount = websiteVisitorDisableRepository.countByAddr(addr);
        int count = websiteVisitorAbnormalRepository.countByAddr(addr);
        if(disableCount>0){
            log.error(addr+"已经被禁止访问");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            // 输出中文内容
            response.getWriter().println("请关注微信公众号：你的公众号哦");

        }else if(count>0){
            log.error(addr+"以列入异常访问中");
            WebsiteVisitorAbnormal websiteVisitorAbnormal = new WebsiteVisitorAbnormal();
            websiteVisitorAbnormal.setId(UUID.randomUUID().toString());
            websiteVisitorAbnormal.setAddr(addr);
            websiteVisitorAbnormal.setMsg("请关注微信公众号：你的公众号哦");
            websiteVisitorAbnormal.setCreatetime(LocalDateTime.now());
            websiteVisitorAbnormal.setUri(request.getRequestURI());
            websiteVisitorAbnormalRepository.save(websiteVisitorAbnormal);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            // 输出中文内容
            response.getWriter().println("请关注微信公众号：你的公众号哦");
        }else{
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }

}
